import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { UserService } from './user.service';
import { JWT_SECRET } from './user.constants';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private userService: UserService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: JWT_SECRET,
    });
  }

  async validate(payload: any) {
    // 验证token对应的用户是否存在 + token是否匹配（防止已退出登录但token未过期）
    const user = await this.userService.findOne(payload.sub);
    if (!user || user.currentToken !== ExtractJwt.fromAuthHeaderAsBearerToken()(payload.req)) {
      throw new UnauthorizedException('登录态已失效，请重新登录');
    }
    return { userId: payload.sub, username: payload.username };
  }
}